package com.yxjx.duoxue.activities;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.Executors;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.stat.StatService;
import com.umeng.socialize.controller.UMSocialService;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.audition.ApointmentAuditionActivity;
import com.yxjx.duoxue.audition.ApointmentDoneActivity;
import com.yxjx.duoxue.course.CourseIntroductionActivity;
import com.yxjx.duoxue.customview.YxDetailedInfoView1;
import com.yxjx.duoxue.customview.YxDetailedInfoView1.YxListAdapter1;
import com.yxjx.duoxue.datamodel.DMActivity;
import com.yxjx.duoxue.datamodel.DMLocationPoints;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.my.UserLoginActivity;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.utils.ShareUtils;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class ActivityIntroductionActivity extends BaseActionBarActivity {
	
	public static final int REQ_CODE_FREE_REG = 1;
	public static final int REQ_CODE_LOGIN_FOR_REG = 2;
	
	private DMActivity mCurActivity = new DMActivity();
	private Context mContext;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_activity_detail);
		customizeActionBarTitle("活动介绍");
		
		mContext = this;
		
		// share function.
		mActionBar.getCustomView().findViewById(R.id.share).setVisibility(View.VISIBLE);
		mActionBar.getCustomView().findViewById(R.id.share).setOnClickListener(mClickListener);
		
		mRegStatus = (TextView) findViewById(R.id.free_reg);
		
		Bundle extra = getIntent().getExtras();
		if (extra == null) {
			return;
		}
		mActivityId = extra.getString(Yx.EXTRA_DM_ACTIVITY_ID);
		
		if (Utils.hasKeyValue(getIntent(), Yx.KEY_OPEN_BY, Yx.VALUE_OPEN_BY_AD_CLICK)) {
			StatHelper.addKVEvent(mContext, "event_home_ad_show", 
					StatHelper.KEY_AD, StatHelper.KEY_ACTIVITY + mActivityId);
		}
		
		LoadingActivityAsyncTask activityTask = new LoadingActivityAsyncTask();
		activityTask.execute("" + mActivityId);
		UIHelper.setClickListener(findViewById(R.id.scrollView1), R.id.school_location, mClickListener);
	}
	
	private void dismissLoadingDialog() {
		findViewById(R.id.root).setVisibility(View.VISIBLE);
		findViewById(R.id.loading).setVisibility(View.INVISIBLE);
	}
	
	private View.OnClickListener mClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.contact:
				StatHelper.addKVEvent(mContext, "event_activity_call_click",
						StatHelper.KEY_ACTIVITY, mActivityId);
				Utils.dialPhoneNumber(v.getContext(),
						mCurActivity);
				break;
			case R.id.free_reg:
				StatHelper.addKVEvent(mContext, "event_activity_reg_click", 
						StatHelper.KEY_ACTIVITY, mActivityId);
				if (mRegStatus.getText().toString().equals("预约成功")) {
					UIHelper.showTips(v, "您已经预约过该活动");
					return;
				}
				
				if (mRemindNum == 0) {
					UIHelper.showTips(v, "活动报名名额已满");
					return;
				}
				
				if (UserLoginResponse.getInstance(getApplicationContext()) != null) {
					bookActivity();
				} else {
					startActivityForResult(new Intent(getApplicationContext(), UserLoginActivity.class), 
							REQ_CODE_LOGIN_FOR_REG);
				}
				break;
			case R.id.school_location:
				StatHelper.addKVEvent(mContext, "event_activity_view_map",
						StatHelper.KEY_ACTIVITY, mActivityId);
				Utils.showLocationsInMap(ActivityIntroductionActivity.this,
						mCurActivity.getAddrList(), mCurActivity.getActivityName());
				break;
				
				
			default:
				mBaseClickListener.onClick(v);
				break;
			}
			
		}
	};
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQ_CODE_FREE_REG:
			if (resultCode == RESULT_OK) {
				mRegStatus.setText("预约成功");
				Toast.makeText(getApplicationContext(), "活动预约成功", Toast.LENGTH_SHORT).show();
			}
		case REQ_CODE_LOGIN_FOR_REG:
			if (resultCode == RESULT_OK) {
				bookActivity();
			}
			break;
		default:
			break;
		}
	};
	
	private String getLocationTag() {
		if (mCurActivity == null) {
			return null;
		}
		DMLocationPoints list = mCurActivity.getAddrList();
		if (list == null || list.getList() == null || list.getList().size() == 0) {
			return "线上活动";
		} else if (list.getList().size() == 1) {
			return list.getList().get(0).getAddress();
		} else {
			return "多商圈";
		}
	}
	
	private void bookActivity() {
		Intent intent = new Intent(getApplicationContext(), ApointmentAuditionActivity.class);
		intent.putExtra(Yx.KEY_SHARE_OBJECT, mCurActivity);
		intent.putExtra(Yx.KEY_BOOK_TYPE, Yx.TYPE_ITEM_ACTIVITY);
		intent.putExtra(Yx.KEY_BOOK_ITEM_ID, mActivityId);
		intent.putExtra(Yx.KEY_BOOK_SCHOOL_NAME, mCurActivity.getHostName());
		intent.putExtra(Yx.KEY_BOOK_ITEM_NAME, mCurActivity.getActivityName());
		startActivity(intent);
	}

	// “免费预约”按钮的状态
	private TextView mRegStatus;
	// 当前页面的ID
	String mActivityId;
	// 剩余名额
	private int mRemindNum;
	
	class LoadingActivityAsyncTask extends AsyncTask<String, Integer, DMActivity> {

		@Override
		protected DMActivity doInBackground(String... arg0) {
			String activityId = arg0[0];
			
			JSONObject params = new JSONObject();
			try {
				params.put(NwUtils.KEY_ID, activityId);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			DMActivity ret = null;
			try {
				ret = (DMActivity) NwUtils.requestDataInfo(NwUtils.REQ_ACTIVITY_INFO, params, ActivityIntroductionActivity.this);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return ret;
		}
		
		@Override
		protected void onPostExecute(DMActivity result) {
			super.onPostExecute(result);
			
			if (result == null) {
				UIHelper.showTips(findViewById(R.id.scrollView1), R.string.check_nw_and_try);
				finish();
				return;
			}
			
			// customzie data
			DMActivity activity = result;
			if (activity != null) {
				mCurActivity = activity;
				
				// share function:
				customizeShare(NwUtils.SHARE_ACTIVITY + "id=" + mActivityId,
						mCurActivity);
				
				UIHelper.setText(findViewById(R.id.scrollView1), R.id.host_by,
						activity.getHostName());
				UIHelper.setText(findViewById(R.id.scrollView1), R.id.location, getLocationTag());
//				UIHelper.setText(findViewById(R.id.scrollView1), R.id.description,
//						activity.getActivityDes());
				UIHelper.setText(findViewById(R.id.scrollView1), R.id.activity_title, activity.getActivityName());
				UIHelper.asyncLoadImage((ImageView) findViewById(R.id.head_image), activity.getHeadImageUrl(), R.drawable.default_banner);
				String data = activity.getActivityDes();
				UIHelper.setText(findViewById(R.id.activity_duration), R.id.activity_duration, 
						Utils.getTimeDuration(activity.getStartTime(), activity.getEndTime()));
				String remindText = "剩余#名额";
				mRemindNum = activity.getActCount() - activity.getActNowCount();
				remindText = remindText.replace("#", "" + (mRemindNum > 0 ? mRemindNum : 0));
				if (mRemindNum > 0) {
				} else {
					remindText = "已报满";
				}
				UIHelper.setText(findViewById(R.id.remind_num), R.id.remind_num, remindText);
				// 电话咨询
				UIHelper.setClickListener(findViewById(R.id.root), R.id.contact, mClickListener);
				UIHelper.setClickListener(findViewById(R.id.root), R.id.free_reg, mClickListener);
				
				if (data != null) {
					data = data.replace("http://file.learnmore.com.cn",
							"http://file.manytu.com");
				}
				
				RichTextHelper rh = new RichTextHelper();
				rh.parseHtmlString(data);
				ArrayList<Object> datas = rh.getData();
				ArrayList<Integer> types = rh.getItemTypes();
				
//				YxDetailedInfoView1 richText = (YxDetailedInfoView1) findViewById(R.id.rich_text_content);
//				YxListAdapter1 mRichTextAdapter = richText.new YxListAdapter1();
//				mRichTextAdapter.setData(types, datas);
//				richText.setAdapter(mRichTextAdapter);
				
				// 加载web view
				WebView webview = (WebView) findViewById(R.id.rich_text_content);
				webview.getSettings().setAppCacheEnabled(true);
				webview.getSettings().setBuiltInZoomControls(false);
				webview.getSettings().setJavaScriptEnabled(true);
		        webview.loadUrl(NwUtils.URL_ACTIVITY_DESC + mActivityId );
				

				final ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView1);
				
				scrollView.post(new Runnable() {
					
					@Override
					public void run() {
						scrollView.scrollTo(0, 0);
						dismissLoadingDialog();
					}
				});
				
				/// MTA stat start
				Properties prop = StatHelper.getBasicProp(ActivityIntroductionActivity.this);
				prop.put(StatHelper.KEY_ACTIVITY, "" + mCurActivity.getActivityId());
				prop.put(StatHelper.KEY_SCHOOL, mCurActivity.getHostName());
				StatService.trackCustomKVEvent(ActivityIntroductionActivity.this, "event_activity_show", prop);
				/// MTA stat end
				
			}
		}
	}

}
